<?php

namespace app\merchant_staff\controller;

use app\admin\model\mycurrency\lease\Orderdevice;
use app\common\controller\MerchantStaff;
use app\common\library\device\cabinet\Analysis;
use app\common\library\device\cabinet\Control;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\mycurrency\Agent;
use app\common\model\mycurrency\DeviceLattice;
use app\common\model\mycurrency\LeaseOrder;
use app\common\model\mycurrency\LeaseOrderDevice;
use app\common\model\mycurrency\LeaseOrderPay;
use app\common\model\mycurrency\MerchantStore;
use fast\Random;
use think\Config;
use think\Exception;
use think\Validate;
use think\Db;

/**
 * 租赁接口
 */
class Lease extends MerchantStaff
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';


    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 租赁订单列表
     */
    public function leaseList(){
        $params = $this->request->param();
        $rule = [
            ['page', 'require', '页码不能为空'],
            ['pageSize', 'require', '每页查询条数不能为空'],
            ['status',"require|in:0,1,2,3", '查询类型不能为空|查询类型错误'],//查询类型：0=全部，1=租赁中，2=待支付，3=已完成
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        if($this->identity == 1){//代理商或业务员
            $store_where = [];
            $agent_ids = [$this->agent['id']];
            if($this->agent['role_type'] == Agent::ROLE_TYPE_DAILI){//代理
                $yewu = Agent::where(['pid' => $this->agent['id'],'role_type' => Agent::ROLE_TYPE_YEWUYUAN])->column('id');
                $agent_ids = array_merge($agent_ids,$yewu);
            }
            $store_where['agent_id'] = ['in',$agent_ids];
            $store_ids = MerchantStore::where($store_where)->column('id');
        }elseif ($this->identity == 2){//门店
            $store_ids = [$this->store['id']];
        }
        $where = [
            'store_id' => ['in',$store_ids],
            'deletetime' => null,
        ];
        switch ($params['status']) {
            case 1:
                $where['use_status'] = LeaseOrder::USE_STATUS_JINXINGZHONG;
                break;
            case 2:
                $where['use_status'] = ['in',[
                    LeaseOrder::USE_STATUS_MIANYA,
                    LeaseOrder::USE_STATUS_YAJIN,
                    LeaseOrder::USE_STATUS_ZHIFUXIANFU,
                    LeaseOrder::USE_STATUS_ZHIFUHOUFU,
                ]];
                break;
            case 3:
                $where['use_status'] = LeaseOrder::USE_STATUS_YIWANCHENG;
                break;
            default:
                $where['use_status'] = ['<>',LeaseOrder::USE_STATUS_YIQUXIAO];
                break;
        }

        $list = LeaseOrder::with([
                'user' => function($query){//会员信息
                    $query->field('id,nickname,mobile');
                },
                'store' => function($query){//门店信息
                    $query->field('id,store_name,status,dorrhead_image');
                },
                'deposit',//免押记录
                'pendingpayment' => function($query){//待支付的租赁费用
                    $query->where([
                        'pay_status' => LeaseOrderPay::PAY_STATUS__DAIZHIFU,
                        'deletetime' => null,
                    ]);
                    $query->order('id desc');
                },
                'rentingingrogressdevice' => function($query){//使用中的设备
                    $query->order('id desc');
                },
            ])
            ->where($where)
            ->limit(($params['page'] - 1) * $params['pageSize'], $params['pageSize'])
            ->order('id desc')
            ->field('*')
            ->select();
        foreach($list as $k => $v){
            $list[$k] = LeaseOrder::getUseStatusText($v);//订单状态
            $list[$k]['operate'] = LeaseOrder::operationJurisdiction($v);//操作权限
            $list[$k]['use_duration'] = timediff(strtotime($v['lease_time']),strtotime($v['return_time']),'str');//使用时长
        }
        $num = LeaseOrder::where($where)->count();
        if ($num > $params['page'] * $params['pageSize']) {
            $nextpage = true;
        } else {
            $nextpage = false;
        }
        $this->success('获取成功', ['list' => $list, 'nextpage' => $nextpage]);
    }


    /**
     * 租赁订单详情
     */
    public function leaseOrderInfo(){
        $params = $this->request->param();
        $rule = [
            ['order_id', 'require', '订单id不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }

        $where = [
            'id' => $params['order_id'],
            'deletetime' => null,
        ];

        $data = LeaseOrder::with([
                'user' => function($query){//会员信息
                    $query->field('id,nickname,mobile');
                },
                'store' => function($query){//门店信息
                    $query->field('id,store_name,status,dorrhead_image');
                },
                'deposit',//免押记录
                'pendingpayment' => function($query){//待支付的租赁费用
                    $query->where([
                        'pay_status' => LeaseOrderPay::PAY_STATUS__DAIZHIFU,
                        'deletetime' => null,
                    ]);
                    $query->order('id desc');
                },
                'rentingingrogressdevice' => function($query){//使用中的设备
                    $query->order('id desc');
                    $query->with(['device' => function($query){
                        $query->field('id,title');
                    },'lattice' => function($query){
                        $query->field('id,number');
                    }]);
                }
            ])
            ->where($where)
            ->field('*')
            ->find();
        $data = LeaseOrder::getUseStatusText($data);
        $data['operate'] = LeaseOrder::operationJurisdiction($data);
        $data['use_duration'] = timediff(strtotime($data['lease_time']),strtotime($data['return_time']),'str');//使用时长
        unset($data['user']['id']);
        $data['device'] = [
            'title' => $data['rentingingrogressdevice']['device']['title'],
            'number' => $data['rentingingrogressdevice']['lattice']['number'],
        ];
        unset($data['rentingingrogressdevice']['device']);
        unset($data['rentingingrogressdevice']['lattice']);
        unset($data['store']['id']);
        unset($data['store']['status_text']);

        $this->success('获取成功', $data);
    }

    /**
     * 结束订单
    */
    public function leaseOrderEnd(){
        $params = $this->request->param();
        $rule = [
            ['order_id', 'require', '订单id不能为空'],
            ['use_end_time', 'require', '结束时间不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $where = [
            'id' => $params['order_id'],
            'deletetime' => null,
        ];
        $order = LeaseOrder::where($where)->find();
        if (!$order){
            $this->error('订单不存在');
        }
        if($order->use_status != LeaseOrder::USE_STATUS_JINXINGZHONG){
            $this->error('订单非使用中状态');
        }
        $order_device = LeaseOrderDevice::where(['lease_order_id' => $order->id])->order(['id desc'])->find();
        if (!$order_device){
            $this->error('设备使用记录不存在');
        }
        Db::startTrans();
        try {
            if ($order_device->status == LeaseOrderDevice::STATUS_ZULINZHONG){//如果是租赁中，说明还没有开始计时 需要先将状态调整为使用中
                LeaseOrder::orderStartRentingResult($order_device->id,1,$order_device->createtime);
            }
            //修改租赁设备记录状态
            $order_device->use_end_time = strtotime($params['use_end_time']);
            $order_device->status = LeaseOrderDevice::STATUS_YIGUIHUAN;
            $order_device->save();
            //结束订单
            trace(["30========================处理lease_order_id报错问题_leaseOrderEnd==============================" => $order_device],'error');
            LeaseOrder::orderEnd($order_device->lease_order_id,strtotime($params['use_end_time']));
            //修改格口状态
            DeviceLattice::where(['id' => $order_device->device_lattice_id])->update([
                'use_status' => DeviceLattice::USE_STATUS_YOUGAN,
            ]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('操作成功');
    }

}
